// 做json
const fs = require("fs");
const Koa = require("koa");
const router = require("koa-router")();

const app = new Koa();

const ExploreData = require("./Data/ExploreData/exploreData.json");
const MovieData = require("./Data/MovieData/movieData.json");
const ShowData = require("./Data/ShowData/showData.json");
const MyData = require("./Data/MyData/myData.json");

const cors = require("koa2-cors");
const Mock = require("mockjs");
const Random = Mock.Random;

app.use(
  cors({
    origin: function (ctx) {
      //设置允许来自指定域名请求
      // if (ctx.url === '/test') {
      return "*"; // 允许来自所有域名请求
      // }
      // return 'http://localhost:3000'; //只允许http://localhost:8080这个域名的请求
    },
    maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //设置所允许的HTTP请求方法
    allowHeaders: ["Content-Type", "Authorization", "Accept"], //设置服务器支持的所有头信息字段
    exposeHeaders: ["WWW-Authenticate", "Server-Authorization"], //设置获取其他自定义字段
  })
);

router.get("/home/explore", async (ctx) => {
  ctx.response.body = {
    success: true,
    data: ExploreData,
  };
});

router.get("/home/movie", async (ctx) => {
  ctx.response.body = {
    success: true,
    data: MovieData,
  };
});

router.get("/home/show", async (ctx) => {
  ctx.response.body = {
    success: true,
    data: ShowData,
  };
});

router.get("/home/my", async (ctx) => {
  ctx.response.body = {
    success: true,
    data: MyData,
  };
});

router.get("/home/recommend", async (ctx) => {
  let { limit = 20, page = 1 } = ctx.request.query;

  let data = Mock.mock({
    "list|20": [

      {'id': "@increment",
        imgsrc: Random.image("165x200", "#9c3319"),
        address: "@city()",
        introduce: "@cword(8,25)",
        date: "@date()",
        time: "@time()",
        day: '@cword("日一二三四五六")',
        'type|1': Random.range(1, 4, 1)
      },
    ],
  });
  data["list"].forEach((item) => {
    item["price"] = ~~(Math.random() * 100) + 1;
  });
  ctx.body = {
    success: true,
    data,
  };
});

router.get("/home/discover", async (ctx) => {
  let { limit = 20, page = 1 } = ctx.request.query;

  let data = Mock.mock({
    "list|20": [
      {
        'id': "@increment",
        imgsrc1: Random.image("165x200", "#1e1e1e"),
        imgsrc2: Random.image("30x30", "#e62fd3"),
        name: "@cword(2,6)",
        text: "@cword(8,28)",
        author: "@cword(3,6)",
        'type|1': Random.range(1, 4, 1)
      },
    ],
  });
  data["list"].forEach((item,index) => {
    item["likeNumber"] = ~~(Math.random() * 100) + 1;
    item["id"]=index+1;
  });

  ctx.body = {
    success: true,
    data,
  };
});

app.use(router.routes()).use(router.allowedMethods());
// 1. http服务
// 2. 简单的路由模块
// 3. cors
// 4. 返回数据
app.listen(9090, () => {
  console.log("server is running 9090");
});
